$(document).ready(
		function() {
			$("html,body").animate({scrollTop: 0}, 100);
			manageReceiveCode('plus', 'default');
			getRequestDescription();
			setDefaultAddress();
		});


//set Default Address
function setDefaultAddress(){	
	$.getJSON('CS63000Srvl', { vaDefaultAddress: "yes" }, function(result) {
		$("#inputContactPostCode").val(result.vaDefaultAddressArray[3]);
		setTimeout( function(){getProvince( result.vaDefaultAddressArray[0]);}, 300);
		setTimeout( function(){ getDistrict( result.vaDefaultAddressArray[0],result.vaDefaultAddressArray[1]);}, 300);
		setTimeout( function(){ getCityCode( result.vaDefaultAddressArray[0],result.vaDefaultAddressArray[1],result.vaDefaultAddressArray[2]);}, 300);			
	});
}

function getRequestDescription(elemId){
	$.ajax({
		url : "CS63000Srvl?process_type=getRequestType",
		type : "POST",
		data : {},
		async : false,
		dataType : 'json',
		success : function(result) {
			var options = '';
			var selected ='';
			options += '<option value="">-- เลือก --</option>';
			for (var i = 0; i < result.values.length; i++) {
				if(elemId == result.values[i]){
					selected = 'selected="selected"';
				}else{
					selected ='';
				}
				options += '<option value="' + result.values[i] + '" '+selected+'>'
						+ result.messages[i] + '</option>';
			}
			$("select#selectRequestDescription").html(options);
		}
	});
}

function toggle() {
	var paCharge = $("input[name=charge]:checked").val();

	if (paCharge == "yes") {
		$("#divReceiveCode").show();
	} else {
		var vnReceiveCount = parseInt($("#inputCountReceiveCode").val());
		for(var i = 0;i<vnReceiveCount;i++){
			$("#input"+(i+1)+"ReceiveRow").popover('destroy');
			
		}
		$("#divReceiveCode").hide();
	}
}

function manageReceiveCode(type, elemId,selectedId,value) {
	var vnAmount;
	if(isNaN(value)== true){
		vnAmount ="";
	}else{
		vnAmount = value;
	}

	$
			.ajax({
				url : "CS63000Srvl?process_type=getReceiveCode",
				type : "POST",
				data : {},
				async : false,
				dataType : 'json',
				success : function(result) {

					var options = '';
					var selected ='';
					options += '<option value="">-- เลือก --</option>';
					for (var i = 0; i < result.values.length; i++) {
						if(selectedId == result.values[i]){
							
							selected = "selected=\"selected\"";
						}else{
							selected = "";
						}
						options += '<option value="' + result.values[i] + '" '+selected+'>'
								+ result.messages[i] + '</option>';
					}
					var maxNumber = 0;
					$("#divReceiveRow").children().each(function() {
						var number = parseInt($(this).prop("id"));
						if (number > maxNumber) {
							maxNumber = number;
						}
					});
					$("#inputCountReceiveCode").val((maxNumber + 1));

					if (type == "plus") {

						var rowId = (maxNumber + 1) + "ReceiveRow";
						var html = "";

						html += "<div class=\"row\" id=\"" + rowId + "\">";
						html += "<div class=\"col-sm-5\">";
						html += "<select class=\"receive-code form-control\" id=\"select"
								+ rowId
								+ "\" name=\"receive_code_"
								+ (maxNumber + 1) + "\">";
						html += options;
						html += "</select>";
						html += "</div>";
						html += "<div class=\"col-sm-3\">";
						html += "<input type=\"text\" class=\"receive-amount form-control\" id=\"input"
								+ rowId
								+ "\" name=\"receive_amount_"
								+ (maxNumber + 1)
								+ "\" placeholder=\"จำนวนเงิน\" value=\""+vnAmount+"\" data-container=\"body\" data-toggle=\"popover\" " 
								+"data-placement=\"right\" data-content=\"กรุณากรอกจำนวนเงินให้ถูกต้อง\" style=\"text-align: right;\"/>";
						html += "</div>";
						html += "<div class=\"col-sm-4\">";
						html += "<label for=\"inputPassword3\" class=\"col-sm control-label\">บาท</label>&nbsp;";
						html += "<button type=\"button\" class=\"plus btn btn-primary\"onclick=\"manageReceiveCode('plus','"
								+ rowId
								+ "')\"><i class=\"glyphicon glyphicon-plus\"></i>";
						html += "</button>&nbsp;";
						html += "<button type=\"button\" class=\"minus btn btn-danger\"onclick=\"manageReceiveCode('minus','"
								+ rowId
								+ "')\"><i class=\"glyphicon glyphicon-minus\"></i>";
						html += "</button>";
						html += "</div>";
						html += "</div>";

						if (elemId == "default") {
							$("#divReceiveRow").html(html);
						} else {
							$(html).insertAfter("#" + elemId);
						}

					} else {
						$("#" + elemId).remove();
					}
					var c = $("#divReceiveRow").children();
					if (parseInt(c.length) > 1) {

						$(".minus").prop("disabled", false);
					} else {
						$(".minus").prop("disabled", true);
					}
				}
			});

}
function confirmSaveData() {
	$('#confirmSaveData').modal();
}
function saveData(elemId) {
	
	//var vnReceiveCount = parseInt($("#inputCountReceiveCode").val());
	var error = false;
	var errorAmount = false;
	var vaCharge = $("input[name=charge]:checked").val();
	$("#inputContactPostCode").popover('destroy');

	if ($("#inputContactPostCode").val() != "") {
		var numbers = /^[ ]*[0-9]{5}[ ]*$/;
		if (!numbers.test($("#inputContactPostCode").val())) {
			$("#inputContactPostCode").focus();
			$("#inputContactPostCode").popover('show');
			$(window).scrollTop($("#inputContactPostCode").offset().top);
			return false;
			error = true;
		}
	}
	$(".receive-amount").each(function(){
		var id = "#"+$(this).prop("id");
		$(id).popover('destroy');
		if(vaCharge == "yes"){
			if ($(this).val() != "") {
				
				var numbers = /^[ ]*[0-9]*[ ]*$/;
				if (isNaN($(this).val())== true) {
					$(id).focus();
					$(id).popover('show');
					$(window).scrollTop($(id).offset().top);
					
					errorAmount = true;
					return false;
					
					
				}
			}else{
				$(id).focus();
				$(id).popover('show');
				$(window).scrollTop($(id).offset().top);
				
				errorAmount = true;
				return false;
			}
		}
	    
	  });
	
	if(errorAmount){
		return false;
	}
	if ($("#inputName").val() == "") {
		error = true;
	}
	if ($("#inputContactHomeNumber").val() == "") {
		error = true;
	}
	if ($("#inputContactCityCode").val() == "") {
		error = true;
	}
	if ($("#inputContactDistrictCode").val() == "") {
		error = true;
	}
	if ($("#inputContactProvinceCode").val() == "") {
		error = true;
	}
	if ($("#inputContactPostCode").val() == "") {
		error = true;
	}
	if ($("#selectRequestDescription").val() == "") {
		error = true;
	}

	if (error == true ) {
		$('#error_message1').removeClass('hide');
//		$(window).scrollTop($("#error_message1").offset().top);
		 $("html,body").animate({scrollTop: 0}, 100);
		
	} else {
		
		var receive_code = [];
		var receive_amount = [];
		var paCharge = $("input[name=charge]:checked").val();
		var i=0;
		$(".receive-code").each(function(){
			
			receive_code[i] = $(this).val();
		    i++;
		  });
			i = 0;
		$(".receive-amount").each(function(){
			
			receive_amount[i] = $(this).val();
			i++;
		  });
		var repetitive = false ;
		for(var i = 0;i< parseInt(receive_code.length) ; i++ ){
			for(var j = 0;j< parseInt(receive_code.length) ; j++ ){
				if(receive_code[i] == receive_code[j] && i != j){
					repetitive = true;
				}
			}
		}
		
		
		if(repetitive == false){
			$('#error_message1').addClass('hide');
			$('#error_message2').addClass('hide');
			$('#error_message3').addClass('hide');
			$('#error_message4').addClass('hide');
			$('#success_message').addClass('hide');
			$
			.ajax({
				url : "CS63000Srvl?process_type=saveData",
				type : "POST",
				data : {
					request_description : $("#selectRequestDescription").val(),
					name : $("#inputName").val(),
					request_detail : $("#textareaRequestDetail").val(),
					contact_home_number : $("#inputContactHomeNumber").val(),
					contact_address : $("#inputContactAddress").val(),
					contact_city_code : $("#inputContactCityCode").val(),
					contact_district_code : $("#inputContactDistrictCode").val(),
					contact_province_code : $("#inputContactProvinceCode").val(),
					contact_post_code : $("#inputContactPostCode").val(),
					contact_telephone : $("#inputContactTelephone").val(),
					charge : paCharge,
					request_num : $("#inputRequestNum").val(),
					receive_code : receive_code,
					receive_amount : receive_amount,
					url_address:$("#url_address").val(),
					agent_browser:$("#agent_browser").val()
					
				},
				async : false,
				dataType : 'json',
				success : function(result) {
					
					if(result.message == "error"){
						
						$('#error_message2').removeClass('hide');
						$('#error_message1').addClass('hide');
						$('#error_message3').addClass('hide');
						$('#success_message').addClass('hide');
						$(window).scrollTop($("#error_message2").offset().top);
					}else{
						var vnUserId = $("#userId").val();
						var vnSiteId = $("#siteId").val();

						var url = reporturl+"CS63000R.jsp?siteId="+vnSiteId+"&userId="+vnUserId+"&requestNumber="+result.RequestNumber;
						window.open(url);
						
						$('#success_message').removeClass('hide');
						$('#error_message1').addClass('hide');
						$('#error_message2').addClass('hide');
						$('#error_message3').addClass('hide');
						$(window).scrollTop($("#success_message").offset().top);
						
						getRequestDescription();
						$("#inputName").val("");
						$("#textareaRequestDetail").val("");
						$("#inputContactHomeNumber").val("");
						$("#inputContactAddress").val("");
						$("select#inputContactCityCode").html('<option value="">-- เลือกตำบล--</option>');
						$("select#inputContactDistrictCode").html('<option value="">-- เลือกอำเภอ --</option>');
						getProvince();
						$("#inputContactPostCode").val("");
						$("#inputContactTelephone").val("");
						$("#inputRequestNum").val("0");
						$("#inputRequestNumber").val("");
						$("#inputCharge").prop("checked", "checked");
						$("#divReceiveRow").html("");
						manageReceiveCode('plus', 'default');
						
						
					}
					
				}
			});
		}else{
			$('#error_message4').removeClass('hide');
			$('#error_message1').addClass('hide');
			$('#error_message2').addClass('hide');
			$('#error_message3').addClass('hide');
			$('#success_message').addClass('hide');
			$(window).scrollTop($("#error_message4").offset().top);
		}
	
		
		
	}
}

function getRequest(){
	$('#success_message').addClass('hide');
	$('#error_message1').addClass('hide');
	$('#error_message2').addClass('hide');
	$('#error_message3').addClass('hide');
	
	var vaRequestNumber = $("#inputRequestNumber").val();
	$
	.ajax({
		url : "CS63000Srvl?process_type=getRequest",
		type : "POST",
		data : {
			
			request_number : vaRequestNumber,
			url_address:$("#url_address").val(),
			agent_browser:$("#agent_browser").val()
		
			
		},
		async : false,
		dataType : 'json',
		success : function(result) {
			getRequestDescription(result.request_description);
			$("#inputName").val(result.name);
			$("#textareaRequestDetail").val(result.request_detail);
			$("#inputContactHomeNumber").val(result.contact_home_number);
			$("#inputContactAddress").val(result.contact_address);
			getProvince(result.contact_province_code);
			getDistrict(result.contact_province_code,result.contact_district_code);
			getCityCode(result.contact_province_code,result.contact_district_code,result.contact_city_code);


			$("#inputContactPostCode").val(result.contact_post_code);
			$("#inputContactTelephone").val(result.contact_telephone);
			$("#inputRequestNum").val(result.request_num);
			
			$("#divReceiveRow").html("");
			
			
			if(parseInt(result.receive_code.length) == 0){
				$("#inputNoCharge").prop("checked", "checked");
				manageReceiveCode('plus', 'default');
				$("#divReceiveCode").hide();
			}else{
				$("#inputCharge").prop("checked", "checked");
				$("#divReceiveCode").show();
				for(var i = 0 ; i < parseInt(result.receive_code.length); i++){
					var elemId = (i)+"ReceiveRow" ;
					if(i == 0){
						manageReceiveCode('plus', 'default',result.receive_code[i],result.receive_amount[i]);
					}else{
						manageReceiveCode('plus', elemId,result.receive_code[i],result.receive_amount[i]);
					}
					
				}
			}
			if(result.message == "no"){
				$("#inputCharge").prop("checked", "checked");
				$("#divReceiveRow").html("");
				manageReceiveCode('plus', 'default');
				$("#divReceiveCode").show();
				$('#error_message3').removeClass('hide');
//				$(window).scrollTop($("#error_message3").offset().top);
				$("html,body").animate({scrollTop: 0}, 100); 
				$("#inputRequestNum").val("0");
			}else{
				$('#error_message3').addClass('hide');
				 
			}
			
		}
	});
	
}